package com.jae.security.exception;

import com.jae.model.ResultCode;
import com.jae.model.ResultMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;

/**
 * 自定义授权异常处理
 */
@Slf4j
public class OAuthServerWebResponseExceptionTranslator implements WebResponseExceptionTranslator {
    @Override
    public ResponseEntity<ResultMsg> translate(Exception e){
        ResultMsg ResultMsg = doTranslateHandle(e);
        return new ResponseEntity<>(ResultMsg, HttpStatus.UNAUTHORIZED);
    }

    private ResultMsg doTranslateHandle(Exception e){
        ResultCode resultCode = ResultCode.UN_AUTHENTICATION;
        if(e instanceof UnsupportedGrantTypeException){
            resultCode = ResultCode.UNSUPPORTED_GRANT_TYPE;
        }else if(e instanceof InvalidGrantException){
            resultCode = ResultCode.USERNAME_OR_PASSWORD_ERROR;
        }
        return new ResultMsg(resultCode.getCode(),false,resultCode.getMessage());
    }


}
